package com.shen.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;



public class MyRandomRule extends AbstractLoadBalancerRule {
    
    public MyRandomRule() {
    }

    /**
     * 规则：每个服务访问五次后换下一个
     *
     * total 存储访问次数
     * index 存储访问第几个服务 默认为0  如果total=5 index+1
     */
    private int total=0; //被调用的次数
    private int currentIndex=0;//当前服务

  //  @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {

        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers();  //获得可以ping到的服务
                List<Server> allList = lb.getAllServers(); // 获得所有可用的服务
                int serverCount = allList.size(); //服务列表数量
                if (serverCount == 0) {
                    return null;
                }

             //   int index = this.chooseRandomInt(serverCount);  在可用的服务数量中生成一个随机值
             //   server = (Server)upList.get(index);      随机获取一个服务
                //--------自定义的算法------------------

                if(total<4){
                    server=upList.get(currentIndex);
                    total++;
                }else{
                    total=0;
                    currentIndex++;
                    if(currentIndex>upList.size()-1){
                        currentIndex=0;
                    }
                    server=upList.get(currentIndex);
                }


                //-------------------------


                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }



    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
